package Socket.TCP;

import com.Utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer implements Runnable{

    public static void main(String... args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(8080);
        while (true) {
            Socket socket = serverSocket.accept();
            new Thread(new MyServer(socket)).start();
        }
    }

    private Socket socket;

    public MyServer(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //读取
            inputStream = socket.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int len;
            while ((len = inputStream.read(buf)) > -1) {
                baos.write(buf, 0, len);
            }
            String msg = new String(baos.toByteArray());
            System.out.println(msg);
            //写出
            outputStream = socket.getOutputStream();
            msg = "处理完请求：" + msg;
            outputStream.write(msg.getBytes());
            outputStream.flush();
            //结束输出
            socket.shutdownOutput();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            Utils.doClose(inputStream);
            Utils.doClose(outputStream);
            Utils.doClose(socket);
        }
    }
}
